﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PanGu;
using System.Text.RegularExpressions;
using System.Xml;
using PatientInformationExtract.Dictionary.Models;
using PatientInformationExtract.MainInterface.Models;
using PatientInformationExtract.Components;

namespace PatientInformationExtract.Dictionary.Views
{
    /// <summary>
    /// Interaction logic for AddWord.xaml
    /// </summary>
    public partial class AddDictionaryWord : Window
    {
        public delegate void AddDictionaryWordHandler(DictionaryWord word, XmlNode catalogNode);
        public event AddDictionaryWordHandler AddDictionaryWordEvent;

        private XmlNode _dictionaryNode;
        private Dictionary<string, XmlNode> _catalogs;
        private XmlNode _catalogNode;

        public AddDictionaryWord(string catalogDisplayName, XmlNode catalogNode)
        {
            InitializeComponent();

            txtName.Focus();

            _catalogNode = catalogNode;
            cmbCatalog.Items.Add(catalogDisplayName);
            cmbCatalog.SelectedIndex = 0;
            cmbCatalog.IsEnabled = false;
            btnTranslate.IsEnabled = (Singleton<MainInterfaceModel>.Instance.Translator != null);
        }

        public AddDictionaryWord(string word, string english, ref Dictionary<string, XmlNode> catalogs)
        {
            InitializeComponent();

            txtName.Text = word;
            Clipboard.Clear();
            Clipboard.SetDataObject(word);
            txtEnglish.Text = english;
            txtName.Focus();
            _catalogs = catalogs;
            foreach (KeyValuePair<string, XmlNode> pair in _catalogs.ToArray())
            {
                if (pair.Value.Name.Equals("Dictionary"))
                {
                    _dictionaryNode = pair.Value;
                    _catalogs.Remove(pair.Key);
                }
            }
            cmbCatalog.ItemsSource = catalogs;
            cmbCatalog.DisplayMemberPath = "Key";
            cmbCatalog.SelectedValuePath = "Value";
            cmbCatalog.SelectedIndex = 2;
            cmbCatalog.IsEnabled = true;
            btnTranslate.IsEnabled = (Singleton<MainInterfaceModel>.Instance.Translator != null);
        }

        public AddDictionaryWord(string word, ref  Dictionary<string, XmlNode> catalogs)
            : this(word, "", ref catalogs)
        {

        }

        public AddDictionaryWord(ref Dictionary<string, XmlNode> catalogs)
            : this("", "", ref catalogs)
        {
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (txtFrequency.Text != "" && txtName.Text != "" && cmbPOS.SelectedIndex != -1)
            {
                txtEnglish.Text = txtEnglish.Text.TrimEnd().TrimStart().ToLower();
                List<string> synonyms = new List<string>();
                foreach (SynonymListViewItem item in lvwSynonym.Items)
                {
                    if (synonyms.Contains(item.Text))
                    {
                        MessageBox.Show(String.Format(DictionaryErrorMessages.AlreadyExists, "Word", item.Text), "Error", MessageBoxButton.OK);
                        return;
                    }
                    synonyms.Add(item.Text);
                }
                DictionaryWord word = new DictionaryWord(txtName.Text, txtEnglish.Text, (POS)Enum.Parse(typeof(POS), cmbPOS.Text), int.Parse(txtFrequency.Text), synonyms);
                if (cmbCatalog.IsEnabled)
                {
                    _catalogNode = cmbCatalog.SelectedValue as XmlNode;
                }

                if (AddDictionaryWordEvent != null)
                {
                    AddDictionaryWordEvent(word, _catalogNode);
                }
                this.Close();
            }
            else
            {
                MessageBox.Show(String.Format(DictionaryErrorMessages.ContentEmpty, "Name or POS or Frequency"));
            }
        }

        private void txtFrequency_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (cmbCatalog.IsEnabled)
            {
                _catalogs.Add(_dictionaryNode.Attributes["Name"].Value, _dictionaryNode);
            }
        }

        private void btnAddSynonym_Click(object sender, RoutedEventArgs e)
        {
            SynonymListViewItem item = new SynonymListViewItem() { IsEnabled = true };
            item.SynonymListViewItemDeletedEvent += new SynonymListViewItem.SynonymListViewItemDeletedHandler(SynonymListViewItemDelete);
            lvwSynonym.Items.Add(item);
        }

        private void SynonymListViewItemDelete(SynonymListViewItem item)
        {
            item.SynonymListViewItemDeletedEvent -= SynonymListViewItemDelete;
            lvwSynonym.Items.Remove(item);
            item = null;
        }

        private void btnTranslate_Click(object sender, RoutedEventArgs e)
        {
            if (txtName.Text != "")
            {
                string translation =null/*= Singleton<MainInterfaceModel>.Instance.CMLPDictHelper.TryGetTranslation(txtName.Text)*/;
                if (String.IsNullOrEmpty(translation))
                {
                    translation = Singleton<MainInterfaceModel>.Instance.Translator.Translate(txtName.Text, "zh-CHS", "en");
                }
                txtEnglish.Text = translation;
                txtEnglish.Focus();
            }
        }

        private void txtEnglish_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.F1))
            {
                txtEnglish.Text = txtEnglish.Text.TrimEnd().TrimStart().ToLower();
            }
            if (e.Key.Equals(Key.Enter))
            {
                btnConfirm.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
            }
        }

        private void MenuItem_Loaded(object sender, RoutedEventArgs e)
        {
            string word = ((((sender as System.Windows.Controls.MenuItem).Parent as ContextMenu).Parent as System.Windows.Controls.Primitives.Popup).PlacementTarget as TextBox).Text;
            MenuItem miUnknownSegmentsAddToDicitonary = (MenuItem)sender;
            miUnknownSegmentsAddToDicitonary.Items.Clear();
            foreach (string segment in word.Split(new char[] { ',' }))
            {
                MenuItem mi = new MenuItem();
                mi.Header = segment.ToLower();
                miUnknownSegmentsAddToDicitonary.Items.Add(mi);
                mi.Click += new RoutedEventHandler(miSelectTranslation_Click);
            }
        }

        private void miSelectTranslation_Click(object sender, RoutedEventArgs e)
        {
            txtEnglish.Text = (sender as MenuItem).Header.ToString();
        }

        private void txtName_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter))
            {
                btnTranslate.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
            }
        }
    }
}
